package com.power.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.power.domain.SysRole;
import com.power.domain.SysRoleMenu;
import com.power.domain.dto.SysRoleDto;
import com.power.mapper.SysRoleMapper;
import com.power.mapper.SysRoleMenuMapper;
import com.power.service.SysRoleMenuService;
import com.power.service.SysRoleService;
import com.power.util.AuthUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.nio.file.AccessDeniedException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService{
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<SysRole> getlist() {
        String key="SYS_USER";
        String json = stringRedisTemplate.opsForValue().get(key);
        ObjectMapper mapper = new ObjectMapper();
        if (StringUtils.hasText(json))
        {
            try {
                List<SysRoleDto> sysRoleDtos = mapper.readValue(json, new TypeReference<List<SysRoleDto>>() {});
                List<SysRole> collect = sysRoleDtos.stream().map(sysRoleDto -> {
                    SysRole sysRole = new SysRole();
                    BeanUtils.copyProperties(sysRoleDto,sysRole);
                    return sysRole;
                }).collect(Collectors.toList());
                return collect;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
        List<SysRole> list = this.list();
        String s1 = JSONObject.toJSONString(list);
        stringRedisTemplate.opsForValue().set(key,s1,60*60, TimeUnit.SECONDS);
        return list;
    }

    @Override
    public Page getPageList(Page<SysRole> page, String name) {
        LambdaQueryWrapper<SysRole> wrapper=new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name))
        {
            wrapper.like(SysRole::getRoleName,name);
        }
        Page<SysRole> page1 = sysRoleMapper.selectPage(page, wrapper);
        return page1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSysRole(SysRole sysRole) {
        if (sysRole==null)
        {
            new AccessDeniedException("参数错误");
        }
        sysRole.setCreateUserId(AuthUtils.getLoginUserId());
        boolean save = this.save(sysRole);
        if (save)
        //如果保存成功的话就向关系表里面添加数据
        {
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            List<Long> menuIdList = sysRole.getMenuIdList();
            if (menuIdList!=null&&menuIdList.size()>0)
            {
                for (long menuId : menuIdList)
                {
                    SysRoleMenu sysRoleMenu=new SysRoleMenu();
                    sysRoleMenu.setRoleId(sysRole.getRoleId());
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenus.add(sysRoleMenu);
                }
                boolean b = sysRoleMenuService.saveBatch(sysRoleMenus);
                return b;
            }
        }
        return false;

    }

    @Override
    public SysRole getInfoById(Long id) {
        if (!StringUtils.isEmpty(id))
        {
            new AccessDeniedException("参数错误");
        }
        SysRole sysRole= this.getById(id);
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
        List<Long> menuIdList = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        sysRole.setMenuIdList(menuIdList);
        return sysRole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByIdMenu(SysRole sysRole) {
        if (sysRole==null)
        {
            new AccessDeniedException("参数错误");
        }
        boolean b = this.updateById(sysRole);
        if (b)
        {
            //先删除关系表里面的数据
            sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,sysRole.getRoleId()));
            //删除成功后然后再添加
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            sysRole.getMenuIdList().forEach(menuId -> {
                SysRoleMenu sysRoleMenu=new SysRoleMenu();
                sysRoleMenu.setRoleId(sysRole.getRoleId());
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenus.add(sysRoleMenu);
            });
            boolean i =sysRoleMenuMapper.insertS(sysRoleMenus);
            return i;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeBatchByIdsMenu(List<Long> ids) {
        if (ids!=null&&ids.size()>0)
        {
            //删除关系表里面的数据
            LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
            ids.forEach(id -> {
                queryWrapper.eq(SysRoleMenu::getRoleId,id);
                sysRoleMenuService.remove(queryWrapper);
            });
            //再删除主表里面的数据
            int i = sysRoleMapper.deleteBatchIds(ids);
            return i>0;
        }
        return false;
    }
}
